package com.example.canteen.dao.impl;

import com.example.canteen.dao.CanteenDao;
import com.example.canteen.domain.Canteen;
import com.example.canteen.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CanteenDaoImpl implements CanteenDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Canteen findById(int id) {
        Canteen canteen = null;
        String sql = "SELECT id,location,statement FROM canteen  WHERE id=?";

        try {
            canteen =template.queryForObject(sql,new BeanPropertyRowMapper<Canteen>(Canteen.class),id);
        }catch (Exception e){

        }
        return canteen;
    }

    @Override
    public List<Canteen> findAll() {
        String sql = "SELECT id,location,statement FROM canteen";
        return template.query(sql, new BeanPropertyRowMapper<Canteen>(Canteen.class));
    }


    @Override
    public int delete(int id) {
        String sql = "DELETE FROM canteen WHERE id=?";
        return template.update(sql,id);
    }

    @Override
    public void save(Canteen canteen) {
        String sql = "insert into canteen(id,location,statement) value(?,?,?)";
        template.update(sql,canteen.getId(),
                canteen.getLocation(),
                canteen.getStatement());

    }

    @Override
    public int update(Canteen canteen) {
        String sql = "UPDATE canteen SET location=?,statement=? WHERE id=?";
        return template.update(sql,canteen.getLocation(),
                canteen.getStatement(),
                canteen.getId());

    }
}
